<?php

/**
 * Twoir CMS系统 twCMS
 *
 * (c) cighsen02 <xiayu@959602.com>
 *
 * Create at：2024.10.14
*/

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\View\View;

class ProfileController extends Controller
{
     /**
     * Show the application dashboard.
     *
     * @param  string  $accountType
     * @return View
     */
    public function index(string $accountType): View
    {
        $user = Auth::user()->load('add');

        return view('auth.profile', ['title' => '我的信息', 'accountType' => $accountType, 'user' => $user]);
    }

    /**
     * 维护用户信息
     *
     * @return RedirectResponse
     */
    public function store(Request $request, string $accountType): RedirectResponse
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required',
            'confirm_password' => 'required_with:password|same:password',
            'avatar' => 'image',
        ]);

        $input = $request->all();

        if ($request->hasFile('avatar')) {
            $avatarName = time().'.'.$request->avatar->getClientOriginalExtension();
            $request->avatar->move(public_path('avatars'), $avatarName);

            $input['avatar'] = $avatarName;
        }
        else {
            unset($input['avatar']);
        }

        if ($request->filled('password')) {
            $input['password'] = Hash::make($input['password']);
        }
        else {
            unset($input['password']);
        }

        Auth::user()->update($input);

        return back()->with('success', 'Profile updated successfully.');
    }
}
